package org.benxiong.iplay.service;

import android.graphics.Bitmap;
import android.util.LruCache;

public class CacheService {

	private static LruCache<String, Bitmap>	mMemoryCache;
	// TODO: diskcache

	static {
		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

		// Use 1/4th of the available memory for this memory cache.
		final int cacheSize = maxMemory / 4;

		mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				// The cache size will be measured in kilobytes rather than
				// number of items.
				return bitmap.getByteCount() / 1024;
			}
		};
	}

	public static void addBitmapToCache(String key, Bitmap bitmap, boolean useDisk) {
		CacheService.addBitmapToMemoryCache(key, bitmap);
		if (useDisk) {
			// TODO: from disk
		}
	}

	public static Bitmap getBitmapFromCache(String key, boolean useDisk) {
		Bitmap bitmap = mMemoryCache.get(key);
		if (bitmap == null) {
			// TODO: from disk
		}
		return bitmap;
	}

	private static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
		if (getBitmapFromMemCache(key) == null) {
			mMemoryCache.put(key, bitmap);
		}
	}

	private static Bitmap getBitmapFromMemCache(String key) {
		return mMemoryCache.get(key);
	}
}
